package ui;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import util.CapsJdbc;
import util.CapsRes;
import util.CapsTableView;

import java.net.URL;
import java.util.*;

public class DeptMgr implements Initializable {

   @FXML
   private TextField dno;

   @FXML
   private TextField name;

   @FXML
   private TextArea remark;

   @FXML
   private TextField deptCond;

   @FXML
   private TableView<Map<String,String>> deptTv;

   @FXML
   private void saveDept(ActionEvent event) {
      List<Object> params = new ArrayList<>(Arrays.asList(name.getText(),remark.getText(),dno.getText()));
      String updSql = "update dept set name=?,remark=? where dno=?";
      CapsRes capsRes = CapsJdbc.execSQL(updSql,params);
      if (capsRes.getTtlNum() < 1) {
         String addSql = "insert into dept(name,remark,dno) values(?,?,?)";
         CapsJdbc.execSQL(addSql,params);
      }
      this.dealQry(null);
   }

   @FXML
   private void qryByDept(ActionEvent event) {
      this.dealQry(deptCond.getText());
   }

   @Override
   public void initialize(URL url, ResourceBundle rb) {
//      deptTv.getSelectionModel().selectedItemProperty()
//              .addListener((observable,  oldValue, newValue) -> {
//
////                 System.out.println("observable:"+observable.getValue()+";oldValue:"+oldValue
////                         +";newValue:"+newValue);
//              });
      this.dealQry(null);
   }

   private void dealQry(String deptName) {
      String strSQL = "select dno,name,remark from dept";
      List<Object> params = null;
      if (null != deptName && deptName.length() > 0) {
         strSQL += " where name like ?";
         params = new ArrayList<>(1);
         params.add(deptName+"%");
      }
      CapsRes capsRes = CapsJdbc.execSQL(strSQL,params);
      CapsTableView.dealTableView(capsRes,deptTv);
      CapsTableView.addButtonToTable(deptTv,(recMap,idCol) -> {
         String delSql = "delete from dept where dno = ?";
         List<Object> delParams = new ArrayList<>(1);
         delParams.add(recMap.get("dno"));
         CapsJdbc.execSQL(delSql,delParams);
         this.dealQry(null);
      },(recMap,idCol) -> {
           dno.setText(recMap.get("dno"));
           name.setText(recMap.get("name"));
           remark.setText(recMap.get("remark"));
      });
   }
}
